/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.dat076.datesite.controllers;

import edu.chl.dat076.datesite.ejbs.UserEJBLocal;
import edu.chl.dat076.datesite.entities.SiteUser;
import java.io.Serializable;
import java.util.Map;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Daniel
 * @author Mikey
*/
@ManagedBean
@ViewScoped
public class LoginControllerBean implements Serializable {
    
    
    @EJB
    private UserEJBLocal userJPACtrl;
    private SiteUser user = new SiteUser();
    
    private String passwordOne;
    private String passwordTwo;
    
    public String register(){
        String message;
        if (passwordOne.equals(passwordTwo)) {
            if (!userJPACtrl.usernameTaken(user.getUsername())){
				Map<String, Object> sessionMap = FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap();
                user.setPassword(passwordOne);
                userJPACtrl.createUser(user);
				sessionMap.put("user", userJPACtrl.getUser(user.getUsername()));
                return "onLogin";
            }
            else {
                message = "User already exists.";
            }
        }
        else {
            message = "Password fields do not match.";
        }
        FacesContext.getCurrentInstance().addMessage("Registration", new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message)); 
        return "onLoginFail";
    }
    
    public String login(){
        Map<String, Object> sessionMap = FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap();
        
        
        
        if (userJPACtrl.okLogin(user.getUsername(), user.getPassword())){
            sessionMap.put("user", userJPACtrl.getUser(user.getUsername()));
            return "onLogin";
        }
        FacesContext.getCurrentInstance().addMessage("Login", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Authentication failed.", "Authentication failed."));
        return "onLoginFail";
    }

    public SiteUser getUser() {
        return user;
    }

    public String getPasswordOne() {
        return passwordOne;
    }

    public void setPasswordOne(String passwordOne) {
        this.passwordOne = passwordOne;
    }

    public String getPasswordTwo() {
        return passwordTwo;
    }

    public void setPasswordTwo(String passwordTwo) {
        this.passwordTwo = passwordTwo;
    }
    
    
    
    
}
